<template>
  <div style="display: flex; flex-direction: column;">
    <el-upload
        ref="refUpload"
        v-model:file-list="fileList"
        class="upload-img-preview"
        list-type="picture-card"
        accept="image/*"
        action=""
        :http-request="httpRequest"
        :multiple="props.mode == 'multi'"
        :auto-upload="false"
        :limit="uploadNumberLimit()"
        :before-upload="beforeUpload"
        :on-success="onUploadSuccess"
        :on-error="onUploadError"
        :on-exceed="onUploadExceedTip">
      <el-icon><Plus /></el-icon>
    </el-upload>
    <div style="display: flex; justify-content: flex-end; margin: 16px">
      <el-button type="danger" @click="cancel">取消</el-button>
      <el-button type="primary" @click="onUploadConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, nextTick} from "vue";
import {msgError} from "@/utils/InfoUtil";
import {Plus} from "@element-plus/icons-vue";

const props = withDefaults(defineProps<{
  tag: string,
  mode?: string,
  maxCount?: number,
  cancel?: any,
  upload?: any,
  uploadSuccess?: any,
}>(), {
  maxCount: 8,
  mode: 'multi',
  cancel: () => {},
});

const refUpload = ref();
const fileList = ref();
const uploadLimit = ref(props.maxCount);
const uploadImages = ref([]);

/**
 * 上传图片
 */
const httpRequest = async (event: any) => {
  const file = event.file
  if (props.upload) {
    await props.upload(file);
  }
  event.onSuccess();
}

const uploadNumberLimit = () => {
  if (!uploadLimit.value) {
    return 1
  }

  return uploadLimit.value - uploadImages.value.length
}

/**
 * 上传图片前检查合法性
 * @param file
 * @returns {boolean}
 */
const beforeUpload = (file: any) => {
  const typeArray = file.type.split('/')
  if (typeArray[0] !== 'image') {
    msgError('请选择上传文件')
    return false
  }
  const isSize = file.size / (1024 * 1024) < 2
  if (!isSize) {
    msgError('上传文件不能大于2M')
    return false
  }

  return true
}

/**
 * 上传成功处理，并提交图片数据
 * @param response
 * @param file
 * @param fileList
 * @returns {boolean}
 */
const onUploadSuccess = (response: any, file: any, fileList: any) => {
  const filesNames: any = []
  fileList.forEach((file: any) => {
    filesNames.push(file.name)
  })
  const uploadFile: any = [];

  if (props.uploadSuccess) {
    props.uploadSuccess(filesNames);
  }
}

/**
 * 上传错误处理
 * @param err
 * @param file
 * @param fileList
 */
const onUploadError = (err: any, file: any, fileList: any) => {
  msgError('上传图片错误')
  throw err
}

/**
 * 选择上传文件超过限制文件个数提示
 */
const onUploadExceedTip = () => {
  msgError(`最多还能选择 ${uploadNumberLimit()}文件`)
}

/**
 * 获取上传图片数据
 */
const onUploadConfirm = () => {
  const fileNum = fileList.value.length;
  nextTick(() => {
    refUpload.value.submit()
  })
}


</script>
